package com.zf.yichat.api.controller.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.*;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.mapper.UserTradeMapper;
import com.zf.yichat.mapper.UserWithdrawMapper;
import com.zf.yichat.model.*;
import com.zf.yichat.service.*;
import com.zf.yichat.service.config.ConfigPay;
import com.zf.yichat.service.config.RedisService;
import com.zf.yichat.utils.HJpay.com.sdk.entity.Response;
import com.zf.yichat.utils.HJpay.com.sdk.entity.WithdrawResponse;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.GeneralUtils;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.common.SysInternPool;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.DictKey;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 14:18 2019/8/14 2019
 */
@RequestMapping("pay")
@Controller
public class PayController extends BaseController {


    @Autowired
    private UserService userService;

    // 汇聚支付
    @Autowired
    private PayService payService;

    // 新生支付
    @Resource
    private XsPayService xsPayService;

    @Autowired
    private BalanceService balanceService;

    @Autowired
    private ConfigPay configPay;

    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private UserTradeMapper userTradeMapper;

//    @RequestMapping("/weixin/pre")
//    @ResponseBody
//    public FsResponse weixinpay(@RequestBody WeixinPayRequest request) {
//        request.valid();
//
//        User user = userService.selectById(getUserId());
//        Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());
//        Contracts.assertTrue(user.getStatus().compareTo(FsConst.Status.EFFECT) == 0, YiChatMsgCode.SYSTEM_USER_CLOSE.msg());
//
//        return FsResponseGen.successData(payService.weixinPrePay(getUserId(), request.getType(), request.getMoney()));
//
//    }

//    @PostMapping("/xspay/open-account")
//    @ResponseBody
//    public FsResponse xspayOpenAccount(@RequestBody WeixinPayRequest request) {
//        Contracts.assertNotNull(request.getBankId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
//
//        return payService.xspayOpenAccount(getUserId().longValue(), request.getBankId());
//    }

    // 汇聚支付

    /**
     * 汇聚支付预绑卡，不包含开户
     * @param params
     * @return
     */
    @PostMapping("/xspay/bind-card/pre2")
    @ResponseBody
    public FsResponse hjPayBindCardPre(@RequestBody UserBankCardAddRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();
            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }
            UserBank bank = new UserBank();
            bank.setUserId(getUserId());
            bank.setStatus(0);
            bank.setBankName(params.getBankName());
            bank.setBankNumber(params.getBankNumber());
            if(params.getName()==null){
                User user=userService.selectById(getUserId());
                bank.setName(user.getRealName());
            }else {
                bank.setName(params.getName());
            }

            bank.setChildBankname(params.getChildBankName());
            //bank.setPassword(params.getPassword());
            bank.setIdNumber(params.getIdNumber());
            bank.setMobile(params.getMobile());

            return payService.sandBindCard(getUserId(), bank);
        }
    }

    /**
     * 汇聚支付预绑卡，不包含开户
     * @param params
     * @return
     */
    @PostMapping("/xspay/bind-card/uu")
    @ResponseBody
    public FsResponse bindCardUu(@RequestBody UserBankCardAddRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();
            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }
            UserBank bank = new UserBank();
            bank.setUserId(getUserId());
            bank.setStatus(0);
            bank.setBankName(params.getBankName());
            bank.setXsbankcode("USDT");
           bank.setBankNumber(params.getBankNumber());
            if(params.getName()==null){
                User user=userService.selectById(getUserId());
                bank.setName(user.getRealName());
                bank.setIdNumber(user.getIdNumber());
                bank.setMobile(user.getMobile());
            }else {
                bank.setName(params.getName());
            }

            bank.setChildBankname("USDT");
            balanceService.checkPassword(getUserId(),params.getPassword());
            //bank.setPassword(params.getPassword());



            return payService.bindCardUu(getUserId(), bank);
        }
    }
    /**
     * 汇聚支付-绑定支付宝
     * @param params
     * @return
     */
    @PostMapping("/xspay/bind-card/aliPay")
    @ResponseBody
    public FsResponse bindCardAliPay(@RequestBody UserBankCardAddRequest params) {
        Long userId = getUserId();
        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            params.valid();
            if (!userService.realValidStatus(userId)) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            UserBank bank = new UserBank();
            bank.setUserId(getUserId());
            bank.setStatus(0);
            // 支付宝名称
            bank.setBankName("支付宝");
            // 支付宝账号
            bank.setBankNumber(params.getBankNumber());

            if(params.getName() == null){
                User user=userService.selectById(getUserId());
                bank.setName(user.getRealName());
                bank.setIdNumber(user.getIdNumber());
                bank.setMobile(user.getMobile());
            }else {
                bank.setName(params.getName());
            }
            // 收款码url
            bank.setChildBankname(params.getChildBankName());
            balanceService.checkPassword(userId, params.getPassword());
            return payService.bindCardAliPay(userId, bank);
        }
    }

    /**
     * 汇聚支付-绑定微信支付
     * @param params
     * @return
     */
    @PostMapping("/xspay/bind-card/weChatPay")
    @ResponseBody
    public FsResponse bindCardweChatPay(@RequestBody UserBankCardAddRequest params) {
        Long userId = getUserId();
        synchronized (SysInternPool.INSTANCE.internUid(userId)) {
            params.valid();
            if (!userService.realValidStatus(userId)) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            UserBank bank = new UserBank();
            bank.setUserId(getUserId());
            bank.setStatus(0);
            // 微信名称
            bank.setBankName("微信");
            // 微信账号
            bank.setBankNumber(params.getBankNumber());

            if(params.getName() == null){
                User user=userService.selectById(getUserId());
                bank.setName(user.getRealName());
                bank.setIdNumber(user.getIdNumber());
                bank.setMobile(user.getMobile());
            }else {
                bank.setName(params.getName());
            }
            // 收款码url
            bank.setChildBankname(params.getChildBankName());
            balanceService.checkPassword(userId, params.getPassword());
            return payService.bindCardWeChatPay(userId, bank);
        }
    }

    /**
     * 汇聚支付预绑卡，不包含开户
     * @param params
     * @return
     */
    @PostMapping("/xspay/bind-card/pre4")
    @ResponseBody
    public FsResponse hjPayBindCardPre4(@RequestBody UserBankCardAddRequest params) {
       // Contracts.assertNotNull(request.getBankId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();
//            if (!userService.realValidStatus(getUserId())) {
//                return FsResponseGen.failMsg("请先实名认证");
//            }

            UserBank bank = new UserBank();
            bank.setUserId(getUserId());
            bank.setStatus(0);
            bank.setBankName(params.getBankName());
            bank.setBankNumber(params.getBankNumber());
            bank.setName(params.getName());
            //bank.setPassword(params.getPassword());
            bank.setIdNumber(params.getIdNumber());
            bank.setMobile(params.getMobile());

            return payService.hjPayBindCardPre(getUserId(), bank);
        }
//   Contracts.assertNotNull(request.getBankId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
//        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
//
//            params.valid();
//            if (!userService.realValidStatus(getUserId())) {
//                return FsResponseGen.failMsg("请先实名认证");
//            }
//
//            UserBank bank = new UserBank();
//            bank.setUserId(getUserId());
//            bank.setStatus(0);
//            bank.setBankName(params.getBankName());
//            bank.setBankNumber(params.getBankNumber());
//            bank.setName(params.getName());
//            //bank.setPassword(params.getPassword());
//            bank.setIdNumber(params.getIdNumber());
//            bank.setMobile(params.getMobile());
//
//            return payService.sandBindCard(getUserId(), bank);
//        }
    }

    /**
     * 汇聚支付预绑卡，不包含开户
     * @param params
     * @return
     */
    @PostMapping("/xspay/bind-card/pre3")
    @ResponseBody
    public FsResponse sandBindCard(@RequestBody UserBankCardAddRequest params) {
//        Contracts.assertNotNull(request.getBankId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();
            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            UserBank bank = new UserBank();
            bank.setUserId(getUserId());
            bank.setStatus(0);
            bank.setBankName(params.getBankName());
            bank.setBankNumber(params.getBankNumber());
            bank.setName(params.getName());
            //bank.setPassword(params.getPassword());
            bank.setIdNumber(params.getIdNumber());
            bank.setMobile(params.getMobile());
            bank.setChildBankname(params.getChildBankName());

            return payService.sandBindCard(getUserId(), bank);
        }
    }


    /**
     * 汇聚支付预绑卡确认
     * @param request
     * @return
     */
    @PostMapping("/xspay/bind-card/confirm2")
    @ResponseBody
    public FsResponse hjPayBindCardConfirm(@RequestBody WeixinPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            Contracts.assertNotNull(request.getOrderCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getNcountOrderId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getSmsCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

//        if (!userService.isValid(getUserId())) {
//            return FsResponseGen.failMsg("请先实名认证");
//        }

            User user = userService.selectById(getUserId());
            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());

            return payService.hjPayBindCardConfirm(request.getOrderCode(), request.getNcountOrderId(), request.getSmsCode());
        }
    }


    private void extracted(StringBuilder sb, String xsuserId, Integer count) {
        try {
            FsResponse fsResponse = payService.xspayGetUserAccount(xsuserId, count);
            if (Objects.isNull(fsResponse)) {
                sb.append(xsuserId).append(":get null\n");
            } else if (!fsResponse.isSuccess()) {
                sb.append(xsuserId).append(":get fail ").append(fsResponse.getMsg());
            } else {
                Map xsMap = (Map) fsResponse.getData();
                BigDecimal money = new BigDecimal(String.valueOf(xsMap.get("balAmount")));
                if (money.compareTo(BigDecimal.ZERO) > 0) {
                    FsResponse transRes = payService.xspayUserTrans(xsuserId, money);
                    if (Objects.isNull(transRes)) {
                        sb.append(xsuserId).append(":trans null\n");
                    } else if (!transRes.isSuccess()) {
                        sb.append(xsuserId).append(":trans fail ").append(transRes.getMsg());
                    }
                }
            }
        } catch (Exception e) {
            sb.append(xsuserId).append(":get e ").append(e.getMessage());
        }

    }

    /**
     * 汇聚支付预支付
     * @param request
     * @return
     */
    @PostMapping("/xspay/pre2")
    @ResponseBody
    public FsResponse hjPayPre(@RequestBody WeixinPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            request.valid();
            Contracts.assertNotNull(request.getBankId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            User user = userService.selectById(getUserId());
            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());

            String orderCode = getUserId() + "pp" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + GeneralUtils.getRandomStringByLength(4);

            return payService.hjPayPre(orderCode, getUserId(), request.getType(), request.getMoney(), request.getBankId());
        }
    }

    /**
     * 汇聚支付预支付确认
     * @param request
     * @return
     */
    @PostMapping("/xspay/confirm2")
    @ResponseBody
    public FsResponse hjPayConfirm(@RequestBody WeixinPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            Contracts.assertNotNull(request.getOrderCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getNcountOrderId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getSmsCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

//            if (!userService.isValid(getUserId())) {
//                return FsResponseGen.failMsg("请先实名认证");
//            }

            return payService.hjPayConfirm(request.getOrderCode(), request.getNcountOrderId(), request.getSmsCode());
        }
    }

    @PostMapping("/hjpay/hjwithdrawfjkldnotify")
    @ResponseBody
    public synchronized void hjPayWithdrawNotify(@RequestBody WithdrawResponse request, HttpServletResponse response) {
        try {
            payService.hjpayWithdrawNotify(request);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("statusCode", "2001");
            response.getWriter().print(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/hjpay/xsfjkldnotify")
    @ResponseBody
    public synchronized void hjPayPayNotify(@RequestBody Response request, HttpServletResponse response) {
        try {
            payService.hjPayNotify(request, response);
            response.getWriter().print("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新生支付回调，提现
     * @param request
     * @param response
     */
    @PostMapping("/xspay/xstxnotify")
    @ResponseBody
    public void xstxnotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.getWriter().print("200");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/trade/status")
    @ResponseBody
    public FsResponse tradeStatus(@RequestBody PayTradeStatusRequest params) {

        params.valid();
        UserTrade trade = balanceService.selectTradeByTradeNo(params.getTradeNo());
        return FsResponseGen.successData(Optional.ofNullable(trade).map(UserTrade::getStatus).orElse(0));
    }

    //新生支付
    /**
     * 新生支付预绑卡，包含开户
     * @param params
     * @return
     */
    @PostMapping("/xspay/bind-card/pre")
    @ResponseBody
    public FsResponse xspayBindCardPre2(@RequestBody UserBankCardAddRequest params) {
//        Contracts.assertNotNull(request.getBankId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            params.valid();
            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            UserBank bank = new UserBank();
            bank.setUserId(getUserId());
            bank.setStatus(0);
            bank.setBankName(params.getBankName());
            bank.setBankNumber(params.getBankNumber());
            bank.setName(params.getName());
            //bank.setPassword(params.getPassword());
            bank.setIdNumber(params.getIdNumber());
            bank.setMobile(params.getMobile());

            return payService.sandBindCard(getUserId(), bank);
        }
    }

    /**
     * 新生支付绑卡确定
     * @param request
     * @return
     */
    @PostMapping("/xspay/bind-card/confirm")
    @ResponseBody
    public FsResponse xspayBindCardConfirm2(@RequestBody WeixinPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {

            Contracts.assertNotNull(request.getOrderCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getNcountOrderId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getSmsCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

//        if (!userService.isValid(getUserId())) {
//            return FsResponseGen.failMsg("请先实名认证");
//        }

            User user = userService.selectById(getUserId());
            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());

            return xsPayService.xspayBindCardConfirm(request.getOrderCode(), request.getNcountOrderId(), request.getSmsCode());
        }
    }

    /**
     * 新生支付预支付，预充值
     * @param request
     * @return
     */
    @PostMapping("/xspay/pre")
    @ResponseBody
    public FsResponse xspayPre2(@RequestBody WeixinPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            request.valid();
            Contracts.assertNotNull(request.getBankId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

//            if (!userService.isValid(getUserId())) {
//                return FsResponseGen.failMsg("请先实名认证");
//            }

            User user = userService.selectById(getUserId());
            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());

            String orderCode = getUserId() + "_" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");

            return xsPayService.xspayPre(orderCode, getUserId(), request.getType(), request.getMoney(), request.getBankId());
        }
    }

    /**
     * 新生支付预支付确认，充值确定
     * @param request
     * @return
     */
    @PostMapping("/xspay/confirm")
    @ResponseBody
    public FsResponse xspayConfirm2(@RequestBody WeixinPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            Contracts.assertNotNull(request.getOrderCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getNcountOrderId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getSmsCode(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

//            if (!userService.isValid(getUserId())) {
//                return FsResponseGen.failMsg("请先实名认证");
//            }

            return xsPayService.xspayConfirm(request.getOrderCode(), request.getNcountOrderId(), request.getSmsCode());
        }
    }

    @PostMapping("/xspay/xsfjkldnotify")
    @ResponseBody
    public synchronized void xspayPayNotify2(HttpServletRequest request, HttpServletResponse response) {
        try {
            xsPayService.xspayNotify(request, response);
            //返回给银联服务器http 200  状态码
            response.getWriter().print("200");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新生支付提现回调
     * @param request
     * @param response
     */
    @PostMapping("/xspay/xstxnotify2")
    @ResponseBody
    public void xstxnotify2(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.getWriter().print("200");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 汇聚支付预支付
     * @param request
     * @return
     */
    @PostMapping("/sandpay/pre")
    @ResponseBody
    public FsResponse sandPay(@RequestBody SandPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            request.valid();

            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            //充值的次数限制
            User user = userService.selectById(getUserId());
            // 今日提现次数
            Example example = new Example(UserTrade.class);
            Date date = new Date();
            example.createCriteria().andEqualTo("userId", getUserId()).andEqualTo("status", 1).andBetween("ctime", DateUtils.formatDate(date, "yyyy-MM-dd 00:00:00"), DateUtils.formatDate(date, "yyyy-MM-dd 23:59:59"));
            int count = userTradeMapper.selectCountByExample(example);
            int maxCount=Integer.parseInt(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_pay_count)).map(SysDict::getMemo).orElse("3"));
            if (count > maxCount-1) {
                return FsResponseGen.failMsg("单日最多充值"+maxCount+"次");
            }
            BigDecimal money=  request.getMoney();
             BigDecimal maxMoney=new BigDecimal(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_pay_max)).map(SysDict::getMemo).orElse("500"));
            if(money.compareTo(maxMoney)>0){
                return FsResponseGen.failMsg("超过单笔最大限额"+maxMoney.toString()+"元");
            }


            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());


            String   phoneList=    Optional.ofNullable(sysDictService.selectOne(DictKey.sys_black_phone)).map(SysDict::getMemo).orElse("0");
            String   idCardList=  Optional.ofNullable(sysDictService.selectOne(DictKey.sys_black_idcard)).map(SysDict::getMemo).orElse("0");
            String orderCode = getUserId() + "pp" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + GeneralUtils.getRandomStringByLength(4);

            if(phoneList.contains(user.getMobile())||idCardList.contains(user.getIdNumber())){
                return FsResponseGen.failMsg("今日充值额度已达上限");
            }

            return payService.sandPayApply( getUserId(),   request.getMoney(),request.getClientIp() );
        }
    }
    /**
     * 汇聚支付预支付
     * @param request
     * @return
     */
    @PostMapping("/sandpay/pre2222")
    @ResponseBody
    public FsResponse sandPay2222(@RequestBody SandPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            request.valid();

            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            //充值的次数限制
            User user = userService.selectById(getUserId());
            // 今日提现次数
            Example example = new Example(UserTrade.class);
            Date date = new Date();
            example.createCriteria().andEqualTo("userId", getUserId()).andEqualTo("status", 1).andBetween("ctime", DateUtils.formatDate(date, "yyyy-MM-dd 00:00:00"), DateUtils.formatDate(date, "yyyy-MM-dd 23:59:59"));
            int count = userTradeMapper.selectCountByExample(example);
            int maxCount=Integer.parseInt(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_pay_count)).map(SysDict::getMemo).orElse("3"));
            if (count > maxCount-1) {
                return FsResponseGen.failMsg("单日最多充值"+maxCount+"次");
            }
            BigDecimal money=  request.getMoney();
            BigDecimal maxMoney=new BigDecimal(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_pay_max)).map(SysDict::getMemo).orElse("500"));
            if(money.compareTo(maxMoney)>0){
                return FsResponseGen.failMsg("超过单笔最大限额"+maxMoney.toString()+"元");
            }


            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());


            String   phoneList=    Optional.ofNullable(sysDictService.selectOne(DictKey.sys_black_phone)).map(SysDict::getMemo).orElse("0");
            String   idCardList=  Optional.ofNullable(sysDictService.selectOne(DictKey.sys_black_idcard)).map(SysDict::getMemo).orElse("0");
            String orderCode = getUserId() + "pp" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + GeneralUtils.getRandomStringByLength(4);

            if(phoneList.contains(user.getMobile())||idCardList.contains(user.getIdNumber())){
                return FsResponseGen.failMsg("今日充值额度已达上限");
            }

            return payService.sandPayApply( getUserId(),   request.getMoney(),request.getClientIp() );
        }
    }

    /**
     * 汇付支付
     * @param request
     * @return
     */
    @PostMapping("/huifu/pre")
    @ResponseBody
    public FsResponse huifuPay(@RequestBody SandPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            request.valid();

            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            //充值的次数限制
            User user = userService.selectById(getUserId());
            // 今日提现次数
            Example example = new Example(UserTrade.class);
            Date date = new Date();
            example.createCriteria().andEqualTo("userId", getUserId()).andEqualTo("status", 1).andBetween("ctime", DateUtils.formatDate(date, "yyyy-MM-dd 00:00:00"), DateUtils.formatDate(date, "yyyy-MM-dd 23:59:59"));
            int count = userTradeMapper.selectCountByExample(example);
            int maxCount=Integer.parseInt(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_pay_count)).map(SysDict::getMemo).orElse("3"));
            if (count > maxCount-1) {
                return FsResponseGen.failMsg("单日最多充值"+maxCount+"次");
            }
            BigDecimal money=  request.getMoney();
            BigDecimal maxMoney=new BigDecimal(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_pay_max)).map(SysDict::getMemo).orElse("500"));
            if(money.compareTo(maxMoney)>0){
                return FsResponseGen.failMsg("超过单笔最大限额"+maxMoney.toString()+"元");
            }

            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());
            String   phoneList=    Optional.ofNullable(sysDictService.selectOne(DictKey.sys_black_phone)).map(SysDict::getMemo).orElse("0");
            String   idCardList=  Optional.ofNullable(sysDictService.selectOne(DictKey.sys_black_idcard)).map(SysDict::getMemo).orElse("0");
            String orderCode = getUserId() + "pp" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + GeneralUtils.getRandomStringByLength(4);

            if(phoneList.contains(user.getMobile())||idCardList.contains(user.getIdNumber())){
                return FsResponseGen.failMsg("今日充值额度已达上限");
            }

            return payService.huifuPayApply( getUserId(),   request.getMoney(),request.getClientIp() );
        }
    }


    /**
     * 支付类型
     *
     * @param
     * @return
     */
    @PostMapping("/payconfig/pre")
    @ResponseBody
    public FsResponse payconfig( ) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {


            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }



            return payService.payconfig( );
        }
    }


    /**
     * 汇聚支付预支付
     * @param request
     * @return
     */
    @PostMapping("/sandpay/h5")
    @ResponseBody
    public FsResponse sandPayH5(@RequestBody SandPayRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            request.valid();

            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            User user = userService.selectById(getUserId());
            Contracts.assertNotNull(user, YiChatMsgCode.USER_INFO_NONE.msg());

            String orderCode = getUserId() + "pp" + DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + GeneralUtils.getRandomStringByLength(4);

            return payService.sandPayApplyH5( getUserId(),   request.getMoney() ,request.getClientIp());
        }
    }
    /**
     * 汇聚支付预支付
     * @param
     * @return
     */
    @PostMapping("/sandpay/callback22")
    @ResponseBody
    public   void sandPayCallBack22(HttpServletRequest request, HttpServletResponse response) {

        payService.sandPayCallBack(request,response);





    }
    /**
     * 汇聚支付预支付
     * @param
     * @return
     */
    @GetMapping("/sandpay/callback")
    @ResponseBody
    public synchronized  void sandPayCallBack(HttpServletRequest request, HttpServletResponse response) {

        payService.sandPayCallBack(request,response);





    }

    /**
     * 汇付回调
     * @param
     * @return
     */
    @RequestMapping("/huifu/callback")
    @ResponseBody
    public   void huifuPayCallBack(HttpServletRequest request, HttpServletResponse response) {

        payService.huifuPayCallBack(request,response);





    }
    /**
     * 获取请求参数中所有的信息
     *
     * @param request
     * @return
     */
    private static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                //System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }
}
